<?php defined('SYSPATH') or die('No direct script access.');

class Model_ProductParser_Tiu extends Model_ProductParser_Abstract
{ 
    protected static $_instance = null;
    
    protected function _get_current_product_id()
    {
        $current_id = DB::select(array(DB::expr('MAX(id)'), 'max'))
            ->from('goods2')
            ->execute()
            ->as_array();
        $current_id = $current_id[0]['max'];
        return $current_id;
    }
    
    public function parse()
    {   
        $categories = $this->_get_categoies();
        
        // TODO
        // если все элементы задания готовы, то очистить задание

        $n = 0;  
        $changed_n = 0; 
        $current_id = $this->_get_current_product_id();
        
		foreach ($categories as $url => $category_id) {
			while ($url) {
				echo $url.'<br />';
				$html = self::_get_source_code($url);
				usleep(700000);
				
				if (strstr($html, 'Защита от роботов') !== false) {
					die('ban');
				}
				if (!$html) {
					continue;    
				}
				
				while ($product = $this->_get_product($html)) {                                  
					$original_id      = $this->_get_product_original_id($product);
					$company_id		  = $this->_get_product_company_id($product);
					$url              = $this->_get_product_url($product);
					$img              = $this->_get_product_picture($product);
					$name             = $this->_get_product_name($product);
					$prices			  = $this->_get_product_prices($product);
					$price            = $this->_get_product_price($product, $prices);
					$currency 		  = $this->_get_product_price_currency($product);
					$description 	  = $this->_get_product_description($product);
					$modified_time    = time();
					
					if (count($prices)) {
						$prices = json_encode($prices);
					} else {
						$prices = null;
					}
										
					try {
						/*echo $original_id.'<br />';
						echo $company_id.'<br />';
						echo $url.'<br />';
						echo $img.'<br />';
						echo $name.'<br />';   
						echo $price.'<br />';
						echo $currency.'<br />';
						echo $description.'<br />';
						print_r($prices);
						echo '<hr>';*/
						//echo '-';
						
						if ($name && $url) {
							$current_id++;  
							
							DB::insert('goods2', array('id', 'original_id', 'original_supplier_id', 'category_id', 'img', 'name', 'price', 
								'currency', 'description', 'prices', 'url'))
									->values(array($current_id, $original_id, $company_id, $category_id, $img, $name, $price,
								$currency, $description, $prices, $url))->execute();
							
							/*DB::insert('product_data', array('product_id'))
									->values(array($current_id))->execute();*/
							$n++;    
						}
					} catch (Database_Exception $e) {
						if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
							$current_id--;      // возвращаем назад идентификатор, т.к. он увеличился, но запись не вставилась
							
							// Перепарсить первые 300 - мультикатегории, описание
							DB::insert('goods2_categories2', array('good_original_id', 'category_id'))
									->values(array($original_id, $category_id))->execute();
							
							/*DB::update('products')
									->set(array('tmp_is_available' => 1))
									->where('original_id', '=', $original_id)
									->where('shop_id', '=', $shop_id)
									->execute();
							if ($changed_rows) {    // цена изменилась
								$product = ORM::factory('product')
											->where('original_id', '=', $original_id)
											->where('shop_id', '=', $shop_id)
											->find();
								DB::delete('product_coupons')
									->where('product_id', '=', $product->id)
									->execute();
								$changed_n++;   
							}*/
							//die($e->getMessage());
						} else {
							die($e->getMessage());
						}
					}               
				}
				//die();
				$url = $this->_get_next_page_url($html);
			}
		}    
        
        //echo 'Changed - '.$changed_n."\n";
        return $n;   
    }
    
    protected function _get_product_original_id($html)
    {
        $source_id = $this->_cut_str('data-paa-product-id="', '"', $html);
		if (!$source_id) {
			$source_id = $this->_cut_str('data-product-id="', '"', $html);
		}
        return $source_id;
    }   

	protected function _get_product_company_id($html)
	{
		$company_id = $this->_cut_str('data-company-id="', '"', $html);
		if (!$company_id) {
			$company_id = $this->_cut_str('data-opinionpopup-company-id="', '"', $html);
		}
		if (!$company_id) {
			$company_id = $this->_cut_str(';wholesale;c', '?per_page=96">', $html);
		}
		if (!$company_id) {
			$company_id = $this->_cut_str('data-rcn-company-id="', '"', $html);
		}
		if (!$company_id) {
			$company_id = $this->_cut_str('tiu.ru/opinions/create/', '?page_type=portal-product_catalog-products_gallery', $html);
		}
        return $company_id;
	}
    
    protected function _get_product_url($html)
    {
        $url = $this->_cut_str('data-product-url="', '"', $html);
		if (!$url) {
			$url = $this->_cut_str('href="', '"', $html);
		}
        return $url;
    }
    
    protected function _get_product_picture($html)
    {
        $image = $this->_cut_str('data-product-big-picture="', '"', $html);
		if (!$image) {
			$image = $this->_cut_str('longdesc="', '"', $html);
		}
		if (!$image) {
			$image = $this->_cut_str('itemprop="image" src="', '"', $html);
		}
        return $image;
    }
    
    protected function _get_product_name($html)
    {
        $name = $this->_cut_str('data-product-name="', '"', $html);
		if (!$name) {
			$name = $this->_cut_str('alt="', '"', $html);
		}
		if (!$name) {
			$name = $this->_cut_str('<span itemprop="name">', '</span>', $html);
		}
        return $name;
    }
	
	protected function _parse_price($price)
	{
		$price = str_replace(' руб.', '', $price);
		$price = str_replace(' ', '', $price);
		$price = str_replace('от', '', $price);
		$price = trim($price);
	
		$new_string = array();
        for ($i = 0; $i < strlen($price); $i++) {
            if (ord($price[$i]) != 194 && ord($price[$i]) != 160 && ord($price[$i]) != 226 /*&& ord($price[$i]) != 128*/ && ord($price[$i]) != 137) {
                $new_string[] = $price[$i];
            }  
        }
        $price = (float)implode('', $new_string);
		return $price;
	}
	
	protected function _get_product_price_currency($html)
	{
		$currency = 'RUR';
		$price = $this->_cut_str('data-product-price="', '"', $html);
		if (strstr($price, '€') !== false) {
			$currency = 'EUR';
		} else if (strstr($price, '$') !== false) {
			$currency = 'USD';
		}
		return $currency;
	}
    
    protected function _get_product_price($html, $prices = array())
    {
        $price = $this->_cut_str('data-product-price="', '"', $html);
        $price = $this->_parse_price($price);
		
		$price2 = $this->_cut_str("<span class=''>", '</span>', $html);
		if (!$price2) {
			$price2 = strip_tags($this->_cut_str('<span itemprop="price">', '</span>', $html));
		}
		$price2 = $this->_parse_price($price2);
		
		if (!$price) {
			$price = $price2;
		} else if ($price2 && $price2 < $price) {
			$price = $price2;
		}
		
		if (!$price) {
			if (isset($prices[0]['price'])) {
				$price = $prices[0]['price'];
			}
		}
		return $price;
    }
	
	protected function _get_product_prices($html)
    {
		$prices = array();
        $price = $this->_cut_str("<span class='h-font-size-19'>", '</span>', $html);
		$price = $this->_parse_price($price);
		
		$count = $this->_cut_str('<p class="h-color-gray h-mb-5">', '/p>', $html);
		$count = $this->_cut_str('от ', '<', $count);
		
		if ($price) {
			$prices[] = array(
				'price' => $price,
				'count' => $count,
			);
		}
		
		$block = $this->_cut_str('<ul class="b-strip-list b-strip-list_output_list', '</ul>', $html);
		while ($li = $this->_cut_str('<li class="b-strip-list__row h-mv-5">', '</li>', $block)) {
			$price = $this->_cut_str('<span class="b-strip-list__text-name">', '</span>', $li);
			$price = $this->_parse_price($price);
			
			$count = $this->_cut_str('<span class="b-strip-list__text-value">', '</span>', $li);
			$prices[] = array(
				'price' => $price,
				'count' => $count,
			);
		}

        return $prices;
    }
	
	protected function _get_product_description($html)
	{
		$description = $this->_cut_str('<div class="h-mb-20"', '</div>', $html);
		$description = $this->_cut_str('>', '<br><a href=', $description);
        return $description;
	}
    
    protected function _get_product_is_free_shipping($html)
    {
        $is_free_shipping = $this->_cut_str('<strong class="free-s">', '</strong>', $html);
        if ($is_free_shipping) {
            return true;
        }
        return false;
    }
    
    protected function _get_product_orders_count($html)
    {
        $orders_count = $this->_cut_str('<em title="Всего заказов">  Заказы (', ')</em>', $html);
        if ($orders_count) {
            return (int)$orders_count;
        }
        return 0;    
    }
    
    protected function _get_product(&$html)
    {
        $product = $this->_cut_str('<div class="b-product-gallery b-hovered js-product-line js-tracking', 'class="b-company-info__opinions-link', $html);
        if (!$product) {
			$product = $this->_cut_str('<div class="b-product-list b-hovered', '<div data-extend="ProductAdminActions"', $html); 
		}
		return $product;    
    } 
    
    protected function _get_next_page_url($html)
    {
        $href = $this->_cut_str('b-pager__link b-pager__link_type_nav pager_lastitem" href="', '"', $html);
        if ($href) {
            return 'http://tiu.ru'.$href;
        }
        return null;
    } 
    
    protected function _get_original_category_id($url)
    {
        $parts = explode('/', $url);
        if (isset($parts[4])) {
            return $parts[4];   
        }
        return 0;
    }
    
    protected function _get_category_id($original_category_id)
    {
        $categories = $this->_get_categoies();
        foreach ($categories as $url => $category_id) {
            if (strstr($url, '/'.$original_category_id.'/')) {
                return $category_id;    
            }
        } 
        return 0;  
    }
    
    protected function _get_categoies()
    {   
		return array(
		);
	
        /*return array(
			//'http://tiu.ru/Magnezitovye-plity;wholesale;2?per_page=96' => 1,
			//'http://tiu.ru/Pechi;wholesale;5?per_page=96' => 1,
			//'http://tiu.ru/Sportivnye-stenki;wholesale?per_page=96' => 1,
			//'http://tiu.ru/Vintovye-fundamentnye-svai;wholesale?per_page=96' => 1,
		);*/
		
		$categories = DB::select()
            ->from('categories2')
			//->where('id', '>', 300)
			->where('pointer_id', '=', 0)
			//->offset(7600)
			->limit(300)
            ->execute()
            ->as_array();
		foreach ($categories as $category) {
			echo "'{$category['tiu_url']}?per_page=96' => {$category['id']},<br />";
		}
		die();
    }          
}
